<template>
	<view class="circle">
		<scroll-view :scroll-top="scrollTop" scroll-y="true" refresher-enabled="true" :refresher-triggered="triggered"
			@refresherrefresh="onRefresh" :refresher-threshold="50" @scrolltolower="scrolltolower"
			@scroll="handleScroll" class="circle_scroll_view">
			<view class="circle_item" v-for="(item,i) in dataSouse" :key="item?.id">
				<view class="circle_header">
					<image :src="item?.avatar" class="circle_header_img" v-if="item?.avatar"></image>
					<image src="http://qianxueapplet.suoeryun.com/avatar.png" class="circle_header_img" v-else></image>
					<view class="circle_header_right">
						<view class="circle_header_right_top">
							<text>{{item?.realname}}</text>
							<button @click="handleAttention(item)" class="circle_header_btn"
								:class="{followed:item?.izFollow === '0',unFollowed:item?.izFollow === '1'}"
								v-if="item?.izFollow !== '-1'">
								{{item?.izFollow === '1'?'已关注':'关注'}}
							</button>
						</view>
						<view class="circle_text">{{item?.content}}</view>
						<view class="circle_img">
							<template v-if="item?.dynamicType === '0'">
								<image :src="img" v-for="(img,index) in item?.images?.split(',')" :key="img"
									@click="handlePreview(item?.images,index)" mode="aspectFill">
								</image>
							</template>
							<template v-else-if="item?.dynamicType === '1'">
								<view class="circle_video" @click="handleVideoPreview(item?.images)"
									:style="{height: Number(item.high)/3.5 + 'rpx',width:Number(item?.width)/3.5 +'rpx'}">
									<video :src="item?.images" :id="'video' + i" :show-center-play-btn="false"
										:show-fullscreen-btn="false" :show-play-btn="false" :controls="false"
										:style="{height: Number(item.high)/3.5 + 'rpx',width:Number(item?.width)/3.5 +'rpx'}"></video>
									<image src="http://qianxueapplet.suoeryun.com/play.png"></image>
								</view>
							</template>
							<!-- :style="{height:item.high === '1280'?'470rpx':'212rpx'}" -->
						</view>
						<view class="circle_header_right_bottom">
							<text>{{item?.fromToday}}发布</text>
							<text v-if="item?.province">{{item?.province}}</text>
						</view>
						<view class="circle_tag" v-if="item?.activityName">
							<text>#{{item?.activityName}}</text>
						</view>
						<view class="circle_fun">
							<view @click="handleLike(item)">
								<image src="http://qianxueapplet.suoeryun.com/likeSelect.png"
									v-if="item?.izLike === '1'">
								</image>
								<image src="http://qianxueapplet.suoeryun.com/like.png" v-else>
								</image>
								<text :style="{color:item?.izLike === '0'?'#666666':'#FF943C'}">{{item?.likes}}</text>
							</view>
							<view @click="handleComment(item,i)">
								<image src="http://qianxueapplet.suoeryun.com/comments.png"></image>
								<text>{{item?.comment}}</text>
							</view>
							<view @click="handleShare(item)">
								<image src="http://qianxueapplet.suoeryun.com/forward.png"> </image>
								<text>{{item?.relay}}</text>
							</view>
						</view>
					</view>
				</view>
			</view>
			<u-loadmore :status="status" @loadmore="scrolltolower" v-if="status !== 'nomore'"></u-loadmore>
		</scroll-view>
	</view>
	<!-- 评论 -->
	<comment ref="commentRef" @close="handleCommentClose"></comment>
	<!-- 分享 -->
	<customShare ref="shareRef"></customShare>
	<!-- 发布按钮 -->
	<button class="circle_btn" @click="handleRelease">
		<image src="http://qianxueapplet.suoeryun.com/release.png"></image>
	</button>
</template>

<script setup lang="ts">
	import comment from "@/components/comment.vue";
	import customShare from "@/components/customShare.vue";
	import { onUnmounted, reactive, ref, unref } from "vue";
	import { qxPlazaDynamicsList, likeOrUnLike } from '@/config/circle.api';
	import { upload } from '@/config/sys.api';
	import { onLoad, onHide } from '@dcloudio/uni-app';
	import { qxUserConcernAdd } from '@/config/mine.api';


	const triggered = ref(false);
	const scrollTop = ref(0);
	const status = ref('loadmore');
	const dataSouse = ref([]);
	const pagination = reactive({ pageNo: 1, total: 0, pageSize: 10 });
	const commentRef = ref();
	const shareRef = ref();
	const commentIndex = ref(0);
	let distance = 0;
	let indexKey = 0;

	onLoad(() => {
		loadData();
		uni.$on('circleUpdate', _ => {
			pagination.pageNo = 1
			loadData();
		})
	})

	onHide(() => {
		commentRef.value.handleClose();
	})

	onUnmounted(() => {
		uni.$off('circleUpdate');
	})

	/**
	 * 加载数据
	 */
	async function loadData() {
		if (pagination.pageNo === 1) {
			dataSouse.value = [];
		}
		status.value = 'loading';
		const res = await qxPlazaDynamicsList({ ...pagination, publishStatus: '1' });
		triggered.value = false;
		pagination.total = res?.total;
		dataSouse.value?.push(...res?.records);
		if (unref(dataSouse)?.length < pagination.total) {
			status.value = 'loadmore';
		} else {
			status.value = 'nomore';
		}
	}

	/**
	 * 滚动到底部操作
	 */
	function scrolltolower() {
		if (unref(dataSouse)?.length < pagination.total && (unref(dataSouse)?.length / pagination.pageSize == pagination.pageNo)) {
			pagination.pageNo++;
			loadData();
		}
	}

	/**
	 * 自定义下拉刷新被触发
	 */
	function onRefresh() {
		triggered.value = true;
		pagination.pageNo = 1;
		loadData();
	}

	/**
	 * 点赞
	 */
	function handleLike(item) {
		uni.$u.throttle(async function () {
			const res = await likeOrUnLike({ id: item?.id, izLike: item?.izLike === '1' ? '0' : '1' });
			item.izLike = res?.izLike;
			item.likes = res?.likes;
			uni.showToast({
				icon: 'none',
				title: res?.izLike === '1' ? '点赞成功' : '取消点赞'
			});
		}, 1000)
	}

	/**
	 * 评论
	 */
	function handleComment(item, index) {
		commentIndex.value = index;
		//type 1 活动 2图集 3视频 4圈子
		commentRef.value.handleShow({ activityId: item?.id, num: item?.comment, belongId: item?.id, type: '4' });
	}

	/**
	 * 评论回调
	 */
	function handleCommentClose(num) {
		dataSouse.value[unref(commentIndex)]['comment'] = num;
	}

	/**
	 * 分享
	 */
	function handleShare(item) {
		shareRef.value.handleShow({ path: 'pages/circle/circleDetails', scene: `id=${item?.id}`, activityId: item?.id, });
	}

	/**
	 * 发布
	 */
	function handleRelease() {
		uni.showActionSheet({
			itemList: ['发布图文', '发布视频'],
			success: function (res) {
				uni.showLoading()
				if (res.tapIndex === 0) {//图片
					uni.chooseMedia({
						count: 9,
						mediaType: ['image'],
						sourceType: ['album'],
						success: (d) => {
							console.log(d?.tempFiles, 'd?.tempFiles');
							uni.hideLoading();
							uni.setStorageSync('circle_url', d?.tempFiles?.map(item => item?.tempFilePath)?.join(','));
							uni.$u.route('/pages/circle/releaseDynamics', { type: res?.tapIndex });
							// let data = d?.tempFiles?.map(async item => {
							// 	const result = await upload({ filePath: item?.tempFilePath, name: 'file', custom: { toast: false } });
							// 	return result;
							// })
							// Promise.all(data).then((vals) => {
							// 	uni.setStorageSync('circle_url', vals?.join(','));
							// 	uni.hideLoading();
							// 	uni.$u.route('/pages/circle/releaseDynamics', { type: res?.tapIndex });
							// }).catch(err => {
							// 	uni.hideLoading();
							// 	// 失败时返回
							// 	console.log(err)
							// })
						}, fail: _ => {
							uni.hideLoading();
						}
					})
				} else if (res.tapIndex === 1) {//视频
					uni.chooseMedia({
						count: 1,
						mediaType: ['video'],
						sourceType: ['album'],
						success(d) {
							console.log(d?.tempFiles[0], 'video');
							uni.hideLoading();
							uni.setStorageSync('circle_url', d?.tempFiles[0]);
							uni.$u.route('/pages/circle/releaseDynamics', { type: res?.tapIndex });
							uni.hideLoading();
							// upload({ filePath: d?.tempFiles[0]['tempFilePath'], name: 'file', custom: { toast: false } }).then(result => {
							// 	uni.setStorageSync('circle_url', result);
							// 	uni.$u.route('/pages/circle/releaseDynamics', { type: res?.tapIndex });
							// });
						}, fail: _ => {
							uni.hideLoading();
						}
					})
				}
			},
			fail: function (res) {
				console.log(res.errMsg);
			}
		});
	}

	/**
	 * 关注
	 */
	function handleAttention(item) {
		uni.$u.throttle(async function () {
			const res = await qxUserConcernAdd({ izFollow: item?.izFollow === '0' ? '1' : '0', userId: item?.createBy });
			if (!uni.$u.test.object(res)) {
				item.izFollow = res;
			}
		}, 1000)
	}


	/**
	 * 图片预览
	 */
	function handlePreview(imgs, index) {
		uni.previewImage({
			current: index,
			urls: imgs?.split(','),
		})
	}

	/**
	 * 视频预览
	 */
	async function handleVideoPreview(imgs) {
		uni.navigateTo({
			url: '/pages/circle/videoPreview?src=' + imgs,
		})
	}

	/**
	 * 滚动监听
	 */
	function handleScroll(e) {
		// const scrollTop = e.detail.scrollTop;
		// console.log(e, scrollTop, 'e');
		// if (scrollTop == 0) {
		// 	indexKey = 0
		// 	this.current_index = indexKey
		// 	this.setVideo(this.current_index);
		// }
		// if (scrollTop > distance) { //页面向上滚动indexKey
		// if (indexKey + 1 < meigeSP.length && scrollTop >= (meigeSP[indexKey] - 71)) {
		// 	console.log(scrollTop, (meigeSP[indexKey] * 0.95))
		// 	this.current_index = indexKey + 1
		// 	this.setVideo(this.current_index);
		// 	indexKey += 1
		// }
		// } else { //页面向下滚动
		// if (distance - scrollTop < 15) { //每次滚动的距离小于15时不改变  减少setData的次数
		// 	return
		// }
		// if (indexKey - 1 > 0 && scrollTop < meigeSP[indexKey - 1] - 71) {
		// 	indexKey -= 1
		// 	this.current_index = indexKey
		// 	this.setVideo(this.current_index);
		// }
		// }
		// distance = scrollTop
	}
</script>

<style lang="scss" scoped>
	.circle {
		margin-top: 16rpx;

		.circle_scroll_view {
			height: calc(100vh - 16rpx);
		}
	}

	// 发布按钮
	.circle_btn {
		position: fixed;
		right: 28rpx;
		bottom: 48rpx;
		width: 96rpx;
		height: 96rpx;
		background-color: transparent;
		margin: 0;
		padding: 0;
		border-radius: 50%;

		image {
			width: 96rpx;
			height: 96rpx;
		}

		&::after {
			border: 0;
		}
	}
</style>